package com.barnett.http;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.os.Handler;

import com.barnett.utils.L;

/**
 * TODO<普通的网络请求的线程>
 * 
 * @data: 2014-6-4 上午10:30:41
 * @version: V1.0
 */
public class JsonRunnable implements Runnable {
	private String url;
	private String params;
	private OnHttpLinstener onHttpLinstener;
	private static Handler handler = new Handler();

	public JsonRunnable(String url, String params,
			OnHttpLinstener onHttpLinstener) {
		this.url = url;
		this.onHttpLinstener = onHttpLinstener;
		this.params = params;
	}

	@Override
	public void run() {
		L.e("URL:" + url);
		if (params != null) {
			L.e("params-->" + params.toString());
		}
		try {
			if (params != null) {
				Map<String, String> nvps = new HashMap<String, String>();
				nvps.put("paramData", params);
				final String result = HttpRequest.doPost(url, nvps);
				L.e("返回信息---->" + result);
				if (result == null) {
					if (onHttpLinstener != null) {
						handler.post(new Runnable() {
							@Override
							public void run() {
								// TODO Auto-generated method stub
								onHttpLinstener.onFail(-1, "请求失败");
							}
						});
					}
					return;
				}
				JSONObject json = new JSONObject(result);
				if (json.has("result")) {
					String resultStr = json.getString("result");
					if ("1".equals(resultStr)) {
						if (onHttpLinstener != null) {
							handler.post(new Runnable() {
								@Override
								public void run() {
									// TODO Auto-generated method stub
									onHttpLinstener.onSuccess(0, result);
								}
							});
						}
					} else {
						if (onHttpLinstener != null) {
							handler.post(new Runnable() {
								@Override
								public void run() {
									// TODO Auto-generated method stub
									onHttpLinstener.onFail(-1, "请求失败");
								}
							});
						}
					}
				} else {
					if (onHttpLinstener != null) {
						handler.post(new Runnable() {
							@Override
							public void run() {
								// TODO Auto-generated method stub
								onHttpLinstener.onFail(-1, "json格式解析出错");
							}
						});
					}
				}
			}
		} catch (final Exception e) {
			e.printStackTrace();
			if (onHttpLinstener != null) {
				handler.post(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						onHttpLinstener.onFail(-1, "" + e.getMessage());
					}
				});
			}
		}
	}
}